# -*- coding: utf-8 -*-
import json
from flask_admin import BaseView, expose
from flask import jsonify
from flask import flash, url_for, redirect, request, current_app
from flask_wtf import FlaskForm
from wtforms import TextAreaField
from adminApp.views import MyCusView
from adminApp.extensions import db,redis_store
from adminApp.models import Idc,Machine,AqyBandWidth95
from sqlalchemy import func
from datetime import datetime,timedelta
'''
计算带宽95值
'''

class CalcBandWidth95View(MyCusView):

    @expose('/', methods=('GET', 'POST'))
    def index(self):
        # 列出机房
        idcs = [(r.id,r.name,r.machines.count()) for r in db.session.query(Idc).all()]
        # 默认将只查询系统==centos 的机器
        # 查询参数：机房ID(多选)，设备标志(多选),爱奇艺ID(多选)
        marks = db.session.query(Machine.man_mark, func.count('*').label('c'))\
            .filter(Machine.is_centos == True).filter(Machine.man_mark!=None).group_by(Machine.man_mark)
        return self.render('machine/calc_bandwidth95.html', idcs=idcs,marks=marks)

    @expose('/search_result', methods=('GET', 'POST'))
    def search_result(self):

        result = dict()
        idc_ids = request.values.getlist("chkidc_id")
        machine_marks = request.values.getlist("machine_marks")
        deviceids = request.args.get('deviceids')
        timepoint = request.args.get('inp_minuter')

        if timepoint:
            try:
                timepoint = datetime.strptime(timepoint, '%Y-%m-%d %H:%M:%S')
            except:
                result['code'] = 400
                result['msg'] = '时间点参数错误，不能转换为日期'
        else:
            result['code'] = 400
            result['msg'] = '缺少时间点参数错误，请选择'
        if not result.get('code'):
            # 默认将只查询系统==centos 的机器
            # 查询参数：机房ID(多选)，设备标志(多选),爱奇艺ID(多选)
            q = db.session.query(Machine.id,Machine.hostname,Machine.aqy_device_id).filter(Machine.is_centos==True)
            if idc_ids:
                q = q.filter(Machine.idc_id.in_(idc_ids))
            if machine_marks:
                q = q.filter(Machine.man_mark.in_(machine_marks))
            if deviceids:
                q = q.filter(Machine.aqy_device_id.in_(deviceids.split(',')))
            machines = q.order_by(Machine.hostname).all()
            # 遍历ID 获取该设备在该时间点的带宽速率，若获取多个则取其中一个
            # 时间 以该时间点为中心 上下各增加减少 2.5分钟 取时间区域
            timepoint_start = timepoint- timedelta(seconds=150)
            timepoint_end = timepoint+ timedelta(seconds=150)
            find_data = []
            find_machine_data = []
            cant_find_data = []
            find_multi_data = []
            will_calc_data = []
            for k in machines:
                will_calc_data.append([k.id,k.hostname,k.aqy_device_id])
                find = db.session.query(AqyBandWidth95.MbpsSent).filter(AqyBandWidth95.machine_id==k.id)\
                    .filter(AqyBandWidth95.Unix_time>=timepoint_start).filter(AqyBandWidth95.Unix_time<=timepoint_end).all()
                if find:
                    if len(find)>1:
                        find_multi_data.append([k.id, k.hostname, k.aqy_device_id, len(find)])
                        temp=0
                        for r in find:
                            if r.MbpsSent>temp:
                                temp=r.MbpsSent
                        # find_data.append(temp)
                        find_machine_data.append([k.id, k.hostname, k.aqy_device_id, temp])
                    else:
                        # find_data.append(find.MbpsSent)
                        find_machine_data.append([k.id, k.hostname, k.aqy_device_id, find[0].MbpsSent])
                else:
                    cant_find_data.append([k.id,k.hostname,k.aqy_device_id])
            # 从 find_data 中 按 95取值，去掉最大的5%的点然后取最大值
            # 生序排列
            # find_data.sort()
            find_machine_data.sort(key=lambda x:x[3])
            if find_machine_data:
                bandwidth_95_value =round(find_machine_data[round(len(find_machine_data)*0.95)-1][3]/1024/1024)
            else:
                bandwidth_95_value ='以该时间点获取数据为空'
            result['code'] = 200
            result['msg'] = dict(will_calc_data=will_calc_data,find_machine_data = find_machine_data,
                                 cant_find_data=cant_find_data,find_multi_data=find_multi_data,bd95val=bandwidth_95_value)
        print(result)
        return jsonify(result)